package com.linuxgt.idea.plugin;

import com.baidu.translate.demo.TransApi;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;

/**
 * 百度翻译 plugin
 * Created by liuteng on 2016/12/16.
 */
public class BaiduTranslateAction extends AnAction {
    @Override
    public void actionPerformed(AnActionEvent anActionEvent) {
        Project project = anActionEvent.getData(PlatformDataKeys.PROJECT);
        Editor fileEditor = anActionEvent.getData(PlatformDataKeys.EDITOR);
        String userName = getSelectText(fileEditor);
        trans(project, userName);
    }

    /**
     * 调用百度api进行翻译
     *
     * @param project  当前所在项目
     * @param tranText 要翻译的文本
     */
    private void trans(Project project, String tranText) {
        Messages.showMessageDialog(project, String.format("%s", TransApi.getInstance().trans2zh(tranText)), "Information", Messages.getInformationIcon());
    }

    /**
     * 获取到当前选中的文本内容
     *
     * @param fileEditor
     * @return 百度翻译结果
     */
    private String getSelectText(Editor fileEditor) {
        return fileEditor.getCaretModel().getCurrentCaret().getSelectedText();
    }
}
